//
//  CollectViewController.swift
//  XiaoXiangMu1604
//
//  Created by qianfeng on 16/9/29.
//  Copyright © 2016年 SunPiaoLiang. All rights reserved.
//

import UIKit

class CollectViewController: LFNavigationViewController {

    //数据源
    private var dataArray: NSMutableArray?
    
    //滚动视图
    private var scrollView: UIScrollView?
    
    //分页控件
    private var pageCtl: UIPageControl?
    
    //是否删除状态
    private var isDelete = false
    
    //视图已经展示的时候去查询数据
    override func viewDidAppear(animated: Bool) {
        
        super.viewDidAppear(animated)
        
        //查询数据
        let dbManager = LFDBManager()
        
        dbManager.searchAllCollectData { (array) -> Void in
            
            self.dataArray = NSMutableArray(array: array)
            
            //显示UI
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                
                self.showCollectData()
            })
            
        }

        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 导航
        createNav()
        
        //创建滚动视图
        automaticallyAdjustsScrollViewInsets = false
        
        scrollView = UIScrollView(frame: CGRectMake(0,64,KScreenWidth,KScreenHeight-64))
        
        scrollView?.backgroundColor = UIColor(white: 0.7, alpha: 1.0)
        
        scrollView?.pagingEnabled = true
        
        view.addSubview(scrollView!)
        
        //分页控件
        pageCtl = UIPageControl(frame: CGRectMake(90,KScreenHeight-60,200,20))
        
        //pageCtl?.backgroundColor = UIColor.redColor()
        pageCtl?.pageIndicatorTintColor = UIColor.blackColor()
        
        view.addSubview(pageCtl!)
        
        
    }
    //显示收藏的数据
    func showCollectData(){
        
        //清空之前的子视图
        for tmpView in (scrollView?.subviews)!{
            
            if tmpView.isKindOfClass(CollectButton){
                
                tmpView.removeFromSuperview()
                
            }
            
        }
        
        if dataArray?.count > 0{
        
            let cnt = dataArray?.count
            
            let colNum = 3
         
            let btnW:CGFloat = 80
            
            let btnH:CGFloat = 100
        
            let offsetX:CGFloat = 30
            
            let offsetY:CGFloat = 160-64
            
            let spaceX = (KScreenWidth-CGFloat(colNum)*btnW-offsetX*2-20)/CGFloat(colNum-1)
            
            let spaceY:CGFloat = 80
            
            for i in 0..<cnt!{
                
                //先计算页数
                let page = i/9
                
                //计算按钮的行和列
                let rowAndCol = i%9
                
                let row = rowAndCol/colNum
                
                let col = rowAndCol%colNum
                
                let btnX = offsetX + CGFloat(col)*(btnW+spaceX) + CGFloat(page)*KScreenWidth
                
                let btnY = offsetY + CGFloat(row)*(btnH+spaceY)
                
                let btn = CollectButton(frame: CGRectMake(btnX,btnY,btnW,btnH))
                
                //显示数据
                btn.model = dataArray![i] as? CollectModel
                
                //设置删除状态
                btn.isDelete = isDelete
                
               scrollView!.addSubview(btn)
                
                //添加点击事件
                btn.addTarget(self, action: "clickBtn:", forControlEvents: .TouchUpInside)
                
              //设置代理
                btn.delegate = self
                
                //序号
                btn.btnIndex = i
                
                
            }
        
            //设置滚动范围
            var pageCnt = cnt!/9
            
            if cnt! % 9 > 0{
                
                pageCnt += 1
                
            }
            
            scrollView?.contentSize = CGSizeMake(CGFloat(pageCnt)*KScreenWidth,0)
            
            scrollView?.delegate = self
            
            //设置分页控件
            pageCtl?.numberOfPages = pageCnt
            
            pageCtl?.currentPage = 0
                
        }else{
                
                //无收藏
                MyUtil.showAlertMsg("还没有任何收藏的数据", onViewController: self)
                
             }
            
    }
    
    //点击进入详情界面
    func clickBtn(btn:CollectButton){
        
        if isDelete == false{
        
            let detailCrl = DetailViewController()
            
            detailCrl.appId = btn.model?.applicationId
            
            navigationController?.pushViewController(detailCrl, animated: true)
            
          }
            
    }
    
                //创建导航
    func createNav(){
        
        addNavTitle("我的收藏")
        
        addBackButton()
        
        addNavButton("编辑", target: self, action: "editAction:", isLeft: false)
        
    }
    //////////谁调target方法，传过来的参数就是谁
    func editAction(btn:UIButton){
      
        if isDelete == false{
            
            //进入删除状态
            btn.setTitle("完成", forState: .Normal)
            
            for tmpView in (scrollView?.subviews)!{
                
                if tmpView.isKindOfClass(CollectButton){
                    
                    let btn = tmpView as! CollectButton
                    
                    btn.isDelete = true
                    
                }
                
            }
            //修改属性
             isDelete = true
            
        }else{
            
            //回到正常状态
            btn.setTitle("编辑", forState: .Normal)
            
            for tmpView in (scrollView?.subviews)!{
                
                if tmpView.isKindOfClass(CollectButton){
                    
                    let btn = tmpView as! CollectButton
                    
                    btn.isDelete = false
                    
                }
                
            }
            //修改属性
            isDelete = false

        }
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
//MARK:CollectButton的代理
extension CollectViewController:CollectButtonDelegate{
    
    func didDeleteButtonAtIndex(index: Int) {
        
        // 1.从数据库删除
        let model = dataArray![index] as! CollectModel
        
        let dbManager = LFDBManager()
        
        dbManager.deleteWithAppId(model.applicationId!){
            
            (flag) in
            
            if flag == true{
                
                
                //2.从数据源删除
                self.dataArray?.removeObjectAtIndex(index)
                
                //3.重新显示
                self.showCollectData()
                
                
            }else{
                
                MyUtil.showAlertMsg("删除失败", onViewController: self)
                
            }
            
        }
        

        
    }

    
}
//MARK:UIScrollView代理
extension CollectViewController:UIScrollViewDelegate{
    
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        
        let index = Int(scrollView.contentOffset.x/scrollView.bounds.size.width)
        
        pageCtl?.currentPage = index
        
    }
    
    
}